package com.justnow.offer;

import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;

/**
 * @author justnow
 * Created on 2020-09-18
 * Description
 */
public class Solition58 {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<Integer> path = new LinkedList<>();
        List<List<Integer>> res = new LinkedList<>();
        Arrays.sort(nums);
        int len = nums.length;
        boolean[] used = new boolean[len];
        dfs(nums, len, 0, path, res, used);
        return res;

    }

    private void dfs(int[] nums, int len, int depth, List<Integer> path, List<List<Integer>> res, boolean[] used) {
        if (depth == len) {
            res.add(new LinkedList<>(path));
            return;
        }

        for (int i = 0; i < len; i++) {
            if (used[i]) {
                continue;
            }

            // 剪枝条件：i > 0 是为了保证 nums[i - 1] 有意义
            // 写 !used[i - 1] 是因为 nums[i - 1] 在深度优先遍历的过程中刚刚被撤销选择
            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
                continue;
            }

            path.add(nums[i]);
            used[i] = true;
            dfs(nums, len, depth + 1, path, res, used);
            used[i] = false;
            path.remove(path.size() - 1);

        }
    }

    public static void main(String[] args) {
        Solition58 solition58 = new Solition58();
        int[] nums = {3, 3, 0, 3};
        List<List<Integer>> lists = solition58.permuteUnique(nums);
        System.out.println(lists);
    }
}
